<?php
            
use app\model\Util; 
use app\model\Theme; 
use app\model\Worker; 


/**
 * Author: cbw
 * Desc: 抖音商城项目
 * Time: 2021/12/6 10:51 上午
 * Email: 17854288794@163.com
 */

class Flag_Page extends PluginWebPage
{
    /**
     * Desc:礼品记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/8 10:53 上午
     */
    public function main()
    {
        $action = 8;
        global $_G,$_P,$_S,$_C;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $name = isset($_P['name'])?trim($_P['name']):'';
        $page_index = max(1,intval($_P['page']));
        $page_size = 50;
        $page_start = ($page_index-1)*$page_size;
        $status = isset($_P['status'])?$_P['status']:0;
        $shangjiaid = isset($_P['shangjiaid'])?$_P['shangjiaid']:0;
        $gift_id = isset($_P['gift_id'])?$_P['gift_id']:0;
        $recordid = isset($_P['recordid'])?$_P['recordid']:0;
        $shangjia = BeilaiModel::getShangjiaList();
        $gift_type = isset($_P['gift_type'])?$_P['gift_type']:0;
        array_unshift($shangjia,['id'=>0,'name'=>'全部商家']);

        if (empty($_P['createtime']['start'])){
            $starttime =  $start_day =db_fetchcolumn ( 'SELECT min(addtime) FROM ' . tablename ( t_fans ) );
            $start_day =  date('Y-m-d H:i:s',$start_day);
        }else{
//            $starttime = $_P['createtime']['start'];
//            $start_day = date("Y-m-d H:i:s",$_P['createtime']['start']);
            $starttime = strpos($_P['createtime']['start'],' ')?strtotime($_P['createtime']['start']):$_P['createtime']['start'];
            $start_day = date("Y-m-d H:i:s",$starttime);
        }
//        $endtime = !$_P['createtime']['end']?time():$_P['createtime']['end'];
//        $end_day = empty($_P['createtime']['end']) ? date('Y-m-d H:i:s',time()): date("Y-m-d H:i:s",$_P['createtime']['end']) ;
        $endtime = !$_P['createtime']['end']?time():$_P['createtime']['end'];
        $endtime = strpos($endtime,' ')?strtotime($endtime):$endtime;
        $end_day = date("Y-m-d H:i:s",$endtime);

        $search_data = isset($_P['search_data'])?$_P['search_data']:'';
        if ($search_data){
            $search_data = '%'.$search_data.'%';
        }

        $type_arr = BeilaiModel::getFlagTypeCount($themeid);
        $prize_arr = BeilaiModel::getGiftFlagCount($themeid);


        $gift_type_list1 = [];
        $setting1 = BeilaiModel::getRewardByWhere(['themeid'=>$themeid]);
        $tuan_gift_info1 = json_decode($setting1['tuan'],true);
        $order_gift_info1 = json_decode($setting1['order'],true);
        if (is_array($tuan_gift_info1)){
            foreach ($tuan_gift_info1 as $key => $val){
                if ($val['key']=='id'){
                    $tuan_gift_id1 = $val['val'];
                }
            }
            $type_list1 = [
                "title"=>'成团礼',
                "gift_id"=>$tuan_gift_id1,
            ];
            array_push($gift_type_list1,$type_list1);
        }
        if (is_array($order_gift_info1)){
            if ($order_gift_info1 && is_array($order_gift_info1)){
                foreach ($order_gift_info1 as $key => $val){
                    $gift_id1 = $val['gift_id'];
                    $temp_array1 = [
                        "title"=>'邀请'.$val['invite'].'人礼',
                        "gift_id"=>$gift_id1,
                    ];
                    array_push($gift_type_list1,$temp_array1);
                }
            }
        }




        $page_total = BeilaiModel::getUserGift($themeid,$shangjiaid,$search_data,0,0,$start_day,$end_day,$gift_type,$gift_id,$status,$recordid,true);
        $list = BeilaiModel::getUserGift($themeid,$shangjiaid,$search_data,$page_start,$page_size,$start_day,$end_day,$gift_type,$gift_id,$status,$recordid);
        foreach ($list as $kk => $vv)
        {
            if ($vv['status']==2){
                $new_gift_id = $vv['gift_id'];
                $list[$kk]['desc'] = '';
                foreach ($gift_type_list1 as $k1 => $val1){
                    if ($val1['gift_id']==$new_gift_id){
                        $list[$kk]['desc'] = $val1['title'];
                    }
                }
            }else{
                $list[$kk]['desc'] = '';
            }
            $check_name = '';
            if ($vv['workerid']){
                $r = Worker::getWokerName($_S,$themeid,$vv['workerid']);
                $check_name=$r['workername']==1?'后台管理员':$r['workername'];
            }
            $list[$kk]['verify_name'] = $check_name;
        }

        $total = $page_total ;
        //导出礼品记录
        if (checksubmit('export_submit', true)){
            $count = $total;
            $page_limit = 2000;
            $pagesize = ceil($count/$page_limit);
            $header = array(
                'uid' => 'UID', 'nickname' => '昵称','username' => '姓名', 'mobile' => '手机',
                'name' => '礼品名称',  'status' => '礼品类型','hexiao'=>'核销信息','shangjainame'=>'提供商家',
                'created_at'=>'中奖时间'
            );
            $keys = array_keys($header);
            $html = "\xEF\xBB\xBF";
            foreach ($header as $li) {
                $html .= $li . "\t ,";
            }
            $html .= "\n";
//            for ($j = 1; $j <= $pagesize; $j++) {
                $condition="";
                if ($shangjiaid){
                    $condition .= " and a.shangjiaid=$shangjiaid ";
                }
                if ($search_data){
                    $condition .= " AND b.nickname LIKE '".$search_data."'"." or b.mobile LIKE '".$search_data."' "." or b.username LIKE '".$search_data."'";
                }
                if ($gift_id){
                    $condition .= " and a.gift_id=$gift_id ";
                }
                if ($recordid){
                    $condition .= " and a.order_id=$recordid ";
                }
                if ($status){
                    $condition .= " and a.status=$status ";
                }
                if ($start_day && $end_day && $start_day!=$end_day){
                    $condition .= "  and a.created_at between '".$start_day."' and '".$end_day."'";
                }
                if ($gift_type){
                    $condition .= " and a.status=$gift_type";
                }

                $ex_page = $_P['ex_page']?$_P['ex_page']:1;
                $sql = " SELECT a.id,a.uid,a.status,a.gift_id,a.created_at,a.updated_at,a.shangjiaid,a.workerid,b.avatar,b.nickname,b.username,b.mobile,c.name,d.name as shangjainame,f.username as workenname FROM "
                    .tablename(t_shangjia_user_gift)." AS  a ".
                    " LEFT JOIN ".tablename(t_fans)." AS b ON a.uid=b.uid and b.themeid=$themeid".
                    " LEFT JOIN ".tablename(t_shangjia_gift)." AS c ON a.gift_id=c.id and c.themeid=$themeid".
                    " LEFT JOIN ".tablename(t_shangjia)." AS d ON a.shangjiaid=d.id and c.themeid=$themeid".
                    " LEFT JOIN ".tablename(t_record)." AS e ON  e.themeid=$themeid and a.uid=e.uid".
                    " LEFT JOIN ".tablename(t_worker)." AS f ON e.workerid=f.uid and f.themeid=$themeid".
                    " WHERE a.themeid=$themeid and a.can_use=1 and e.status=1".$condition.
                    "   order by a.created_at desc limit ". ($ex_page - 1) * $page_limit . ",$page_limit ";

                $list = db_select($sql);

                //导出判断礼品类型
                $gift_type_list1 = [];
                $setting1 = BeilaiModel::getRewardByWhere(['themeid'=>$themeid]);
                $tuan_gift_info1 = json_decode($setting1['tuan'],true);
                $order_gift_info1 = json_decode($setting1['order'],true);
                if ($tuan_gift_info1){
                    foreach ($tuan_gift_info1 as $key => $val){
                        if ($val['key']=='id'){
                            $tuan_gift_id1 = $val['val'];
                        }
                    }
                }
                $type_list1 = [
                    "title"=>'成团礼',
                    "gift_id"=>$tuan_gift_id1,
                ];
                array_push($gift_type_list1,$type_list1);
                if ($order_gift_info1 && is_array($order_gift_info1)){
                    foreach ($order_gift_info1 as $key => $val){
                        $gift_id1 = $val['gift_id'];
                        $temp_array1 = [
                            "title"=>'邀请'.$val['invite'].'人礼',
                            "gift_id"=>$gift_id1,
                        ];
                        array_push($gift_type_list1,$temp_array1);
                    }
                }
                foreach ($list as $kk => $vv)
                {
                    if ($vv['status']==2){
                        $new_gift_id = $vv['gift_id'];
                        $list[$kk]['desc'] = '';
                        foreach ($gift_type_list1 as $k1 => $val1){
                            if ($val1['gift_id']==$new_gift_id){
                                $list[$kk]['desc'] = $val1['title'];
                            }
                        }
                    }else{
                        $list[$kk]['desc'] = '';
                    }
                    if ($vv['workerid']){
                        $r = Worker::getWokerName($_S,$themeid,$vv['workerid']);
                        $check_name=$r['workername']==1?'后台管理员':$r['workername'];
                        $list[$kk]['hexiao'] = '已核销；员工【'.$check_name.'】在'.$vv['updated_at'].'核销';
                    }else{
                        $list[$kk]['hexiao'] = '未核销';
                    }
                }
                //导出判断礼品类型

                if (!empty($list)) {
                    $size = ceil(count($list) / 500);
                    for ($i = 0; $i < $size; $i++) {
                        $buffer = array_slice($list, $i * 500, 500);
                        foreach ($buffer as $row) {
                            switch ($row['status']){
                                case 1:
                                    $row['status'] = '赠品';
                                    break;
                                case 2:
                                    $row['status'] = $row['desc'];
                                    break;
                                default:
                                    break;
                            }

                            foreach ($keys as $key) {
                                $data[] = $row[$key];
                            }
                            if (isset($data)){
                                $user[] = implode("\t ,", $data) . "\t ,";
                                unset($data);
                            }
                        }
                        $html .= implode("\n", $user)."\n";
                        unset($user);
                    }
                }
//            }
            //新版本导出合并
            $is_end = 0;
            if($ex_page>=$pagesize){
                $is_end = 1;
            }
            Util::WxJump($_S,$html,'礼品记录',$themeid,$is_end,$pagesize);
        }
        $pager = pagination($page_total,$page_index,$page_size);
        $return_clicent = get_defined_vars();
return $this->view('/beilai/flag/main', $return_clicent);
    }

    /**
     * Desc:优惠券记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/8 10:53 上午
     */
    public function coupon()
    {
        $action = 9;
        global $_G,$_P,$_S,$_C;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $name = isset($_P['name'])?trim($_P['name']):'';
        $page_index = max(1,intval($_P['page']));
        $page_size = 50;
        $page_start = ($page_index-1)*$page_size;
        $shangjiaid = isset($_P['shangjiaid'])?$_P['shangjiaid']:0;
        $gift_id = isset($_P['gift_id'])?$_P['gift_id']:0;
        $recordid = isset($_P['recordid'])?$_P['recordid']:0;
        $shangjia = BeilaiModel::getCouponFromCount($themeid);
        $gift_type = isset($_P['gift_type'])?$_P['gift_type']:0;


        if (empty($_P['createtime']['start'])){
            $starttime =  $start_day =db_fetchcolumn ( 'SELECT min(addtime) FROM ' . tablename ( t_fans ) );
            $start_day =  date('Y-m-d H:i:s',$start_day);
        }else{
//            $starttime = $_P['createtime']['start'];
//            $start_day = date("Y-m-d H:i:s",$_P['createtime']['start']);
            $starttime = strpos($_P['createtime']['start'],' ')?strtotime($_P['createtime']['start']):$_P['createtime']['start'];
            $start_day = date("Y-m-d H:i:s",$starttime);
        }
//        $endtime = !$_P['createtime']['end']?time():$_P['createtime']['end'];
//        $end_day = empty($_P['createtime']['end']) ? date('Y-m-d H:i:s',time()): date("Y-m-d H:i:s",$_P['createtime']['end']) ;
        $endtime = !$_P['createtime']['end']?time():$_P['createtime']['end'];
        $endtime = strpos($endtime,' ')?strtotime($endtime):$endtime;
        $end_day = date("Y-m-d H:i:s",$endtime);

        $search_data = isset($_P['search_data'])?$_P['search_data']:'';
        if ($search_data){
            $search_data = '%'.$search_data.'%';
        }

        $type_arr = BeilaiModel::getFlagTypeCount($themeid);
        $prize_arr = BeilaiModel::getGiftFlagCount($themeid);
        $page_total = BeilaiModel::getUserCouponFlag($themeid,$shangjiaid,$search_data,0,0,$start_day,$end_day,$recordid,true);
        $list = BeilaiModel::getUserCouponFlag($themeid,$shangjiaid,$search_data,$page_start,$page_size,$start_day,$end_day,$recordid);
        $total = $page_total ;
        //导出优惠券记录
        if (checksubmit('export_submit', true)){
            $count = $total;
            $page_limit = 2000;
            $pagesize = ceil($count/$page_limit);
            $header = array(
                'uid' => 'UID','nickname' => '昵称', 'username' => '姓名', 'mobile' => '电话',
                'name' => '优惠券名称', 'price'=>'优惠券金额', 'shangjainame' => '优惠券获取渠道','status' => '状态',
                'created_at'=>'领取时间'
            );
            $keys = array_keys($header);
            $html = "\xEF\xBB\xBF";
            foreach ($header as $li) {
                $html .= $li . "\t ,";
            }
            $html .= "\n";
//            for ($j = 1; $j <= $pagesize; $j++) {
                $condition="";
                if ($shangjiaid){
                    $condition .= " and a.shangjiaid=$shangjiaid ";
                }
                if ($recordid){
                    $condition .= " and a.order_id=$recordid ";
                }
                if ($search_data){
                    $condition .= " AND b.nickname LIKE '".$search_data."'"." or b.mobile LIKE '".$search_data."' "." or b.username LIKE '".$search_data."'";
                }
                if ($start_day && $end_day && $start_day!=$end_day){
                    $condition .= "  and a.created_at between '".$start_day."' and '".$end_day."'";
                }
                $ex_page = $_P['ex_page']?$_P['ex_page']:1;

                $sql = " SELECT a.uid,a.status,a.created_at,a.shangjiaid,b.avatar,b.nickname,b.username,b.mobile,c.name,c.price,d.name as shangjainame FROM ".tablename(t_shangjia_user_coupon)." AS  a ".
                    " LEFT JOIN ".tablename(t_fans)." AS b ON a.uid=b.uid and b.themeid=$themeid".
                    " LEFT JOIN ".tablename(t_shangjia_coupon)." AS c ON a.coupon_id=c.id and c.themeid=$themeid".
                    " LEFT JOIN ".tablename(t_shangjia)." AS d ON a.shangjiaid=d.id and c.themeid=$themeid".
                    " LEFT JOIN ".tablename(t_record)." AS e ON e.id=a.order_id and  e.themeid=$themeid".
                    " WHERE a.themeid=$themeid ".$condition.
                    "  order by a.created_at desc limit ". ($ex_page - 1) * $page_limit . ",$page_limit ";

                $list = db_select($sql);

                if (!empty($list)) {
                    $size = ceil(count($list) / 500);
                    for ($i = 0; $i < $size; $i++) {
                        $buffer = array_slice($list, $i * 500, 500);
                        foreach ($buffer as $row) {
                            switch ($row['status']){
                                case 1:
                                    $row['status'] = '未使用';
                                    break;
                                case 2:
                                    $row['status'] = '已使用';
                                    break;
                                default:
                                    break;
                            }

                            foreach ($keys as $key) {
                                $data[] = $row[$key];
                            }
                            if (isset($data)){
                                $user[] = implode("\t ,", $data) . "\t ,";
                                unset($data);
                            }
                        }
                        $html .= implode("\n", $user)."\n";
                        unset($user);
                    }
                }
//            }
            //新版本导出合并
            $is_end = 0;
            if($ex_page>=$pagesize){
                $is_end = 1;
            }
            Util::WxJump($_S,$html,'优惠券领取记录',$themeid,$is_end,$pagesize);
        }
        $pager = pagination($page_total,$page_index,$page_size);
        $return_clicent = get_defined_vars();
return $this->view('/beilai/flag/coupon', $return_clicent);
    }

    /**
     * Desc:课程选择记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/8 10:53 上午
     */
    public function course()
    {
        $action = 10;
        global $_G,$_P,$_S,$_C;
        $config = $_C;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $page_index = max(1,intval($_P['page']));
        $page_size = 50;
        $page_start = ($page_index-1)*$page_size;
        $shangjiaid = isset($_P['shangjiaid'])?$_P['shangjiaid']:0;
        $gift_id = isset($_P['gift_id'])?$_P['gift_id']:0;
        $recordid = isset($_P['recordid'])?$_P['recordid']:0;
        $shangjia = BeilaiModel::getShangjiaList();
        $gift_type = isset($_P['gift_type'])?$_P['gift_type']:0;
        array_unshift($shangjia,['id'=>0,'name'=>'全部商家']);
        $shangjia_info = BeilaiModel::getSjCourseTotal($shangjia,$themeid);

        if (empty($_P['createtime']['start'])){
            $starttime =  $start_day =db_fetchcolumn ( 'SELECT min(addtime) FROM ' . tablename ( t_fans ) );
            $start_day =  date('Y-m-d H:i:s',$start_day);
        }else{
//            $starttime = $_P['createtime']['start'];
//            $start_day = date("Y-m-d H:i:s",$_P['createtime']['start']);
            $starttime = strpos($_P['createtime']['start'],' ')?strtotime($_P['createtime']['start']):$_P['createtime']['start'];
            $start_day = date("Y-m-d H:i:s",$starttime);
        }
//        $endtime = !$_P['createtime']['end']?time():$_P['createtime']['end'];
//        $end_day = empty($_P['createtime']['end']) ? date('Y-m-d H:i:s',time()): date("Y-m-d H:i:s",$_P['createtime']['end']) ;
        $endtime = !$_P['createtime']['end']?time():$_P['createtime']['end'];
        $endtime = strpos($endtime,' ')?strtotime($endtime):$endtime;
        $end_day = date("Y-m-d H:i:s",$endtime);

        $search_data = isset($_P['search_data'])?$_P['search_data']:'';
        if ($search_data){
            $search_data = '%'.$search_data.'%';
        }

        $page_total = BeilaiModel::getUserCourseFlag($themeid,$shangjiaid,$search_data,0,0,$start_day,$end_day,$recordid,1,0,true);
        $list = BeilaiModel::getUserCourseFlag($themeid,$shangjiaid,$search_data,$page_start,$page_size,$start_day,$end_day,$recordid);
        if (!empty($list)){
            foreach ($list as $k => $v){
                if ($v['status'] && $v['workerid']){
                    $check_worker = Worker::getWokerName($_S,$themeid,$v['workerid']);
                    $list[$k]['verify_name'] = $check_worker['workername']==1?'后台管理员':$check_worker['workername'];
                }
            }
        }
        $total = $page_total;
        //导出课程校区记录
        if (checksubmit('export_submit', true)){

            $count = $total;
            $page_limit = 2000;
            $pagesize = ceil($count/$page_limit);
            $header = array(
                'uid' => 'UID','nickname' => '昵称', 'username' => '姓名', 'mobile' => '电话',
                'form_nickanme'=>'邀约人微信昵称');
            if (!empty($config['datetime'])) {
                $header['datetime']= $config['datetime'];
            }
            if (!empty($config['address'])) {
                $header['raddress'] = $config['address'];
            }
            if (!empty($config['formtwo'])) {
                $header['formtwo'] = $config['formtwo'];
            }
            if (!empty($config['addinfo'])) {
                $header['addinfo']= $config['addinfo'];
            }
            if (!empty($config['shops']) && $config['shopstype']!=8 ) {
                $header['option'] = $config['shops'];
            }
            $header2 = array('name' => '课程名称',  'address' => '上课地址','shangjianame'=>'提供商家',
                'status'=>'核销状态','check_name'=>'课程核销人','checked_at'=>'课程核销时间',
                'workenname'=>'员工',
                'created_at'=>'创建时间'
            );
            $header = array_merge($header,$header2);
            $keys = array_keys($header);
            $html = "\xEF\xBB\xBF";
            foreach ($header as $li) {
                $html .= $li . "\t ,";
            }
            $html .= "\n";
//            for ($j = 1; $j <= $pagesize; $j++) {
                $condition="";
                if ($shangjiaid){
                    $condition .= " and a.shangjiaid=$shangjiaid ";
                }
                if ($search_data){
                    $condition .= " AND b.nickname LIKE '".$search_data."'"." or b.mobile LIKE '".$search_data."' "." or b.username LIKE '".$search_data."'";
                }

                if ($recordid){
                    $condition .= " and a.order_id=$recordid ";
                }

                if ($start_day && $end_day && $start_day!=$end_day){
                    $condition .= "  and a.created_at between '".$start_day."' and '".$end_day."'";
                }

                $ex_page = $_P['ex_page']?$_P['ex_page']:1;

                $sql = " SELECT a.id,a.uid,a.shangjiaid,a.address,a.created_at,a.updated_at,a.status,a.workerid,b.avatar,b.nickname,b.username,b.mobile,b.fromuid,c.name,d.name as shangjianame,e.fee,e.mobile as order_mobile,f.username as workenname,g.nickname as form_nickanme
                ,e.datetime,e.address as raddress,e.formtwo,e.addinfo,e.option FROM "
                    .tablename(t_shangjia_address_user_course)." AS  a ".
                    " LEFT JOIN ".tablename(t_fans)." AS b ON a.uid=b.uid and b.themeid=$themeid".
                    " LEFT JOIN ".tablename(t_shangjia_course)." AS c ON a.course_id=c.id and c.themeid=$themeid".
                    " LEFT JOIN ".tablename(t_shangjia)." AS d ON a.shangjiaid=d.id ".
                    " LEFT JOIN ".tablename(t_record)." AS e ON a.order_id=e.id and  e.themeid=$themeid".
                    " LEFT JOIN ".tablename(t_worker)." AS f ON e.workerid=f.uid and f.themeid=$themeid".
                    " LEFT JOIN ".tablename(t_fans)." AS g ON b.fromuid=g.uid and g.themeid=$themeid".
                    " WHERE a.themeid=$themeid and e.status=1 ".$condition.
                    "  order by a.created_at desc limit ". ($ex_page - 1) * $page_limit . ",$page_limit ";

                $list = db_select($sql);


                if (!empty($list)) {
                    $size = ceil(count($list) / 500);
                    for ($i = 0; $i < $size; $i++) {
                        $buffer = array_slice($list, $i * 500, 500);
                        foreach ($buffer as $row) {
                            if ($row['status']){
                                $row['status'] = '已核销';
                            }else{
                                $row['status'] = '未核销';
                            }

                            $check_name = '';
                            if ($row['workerid']){
                                $r = Worker::getWokerName($_S,$themeid,$row['workerid']);
                                $check_name=$r['workername']==1?'后台管理员':$r['workername'];
                            }
                            $row['check_name'] = $check_name;
                            if ($row['status']!='已核销'){
                                $row['checked_at']='';
                            }else{
                                $row['checked_at'] = $row['updated_at'];
                            }
                            if ($row['nickname']){
                                $row['nickname'] = str_replace(',','',$row['nickname']);
                                $row['nickname'] = str_replace('"','',$row['nickname']);
                            }


                            foreach ($keys as $key) {
                                $data[] = $row[$key];
                            }
                            if (isset($data)){
                                $user[] = implode("\t ,", $data) . "\t ,";
                                unset($data);
                            }
                        }
                        $html .= implode("\n", $user)."\n";
                        unset($user);
                    }
                }
//            }
            $is_end = 0;
            if($ex_page>=$pagesize){
                $is_end = 1;
            }
            //新版本导出合并
            Util::WxJump($_S,$html,'用户课程校区选择记录',$themeid,$is_end,$pagesize);
        }
        $pager = pagination($page_total,$page_index,$page_size);
        $return_clicent = get_defined_vars();
return $this->view('/beilai/flag/course', $return_clicent);
    }
}